package Thread;
//测试线程的notify 和wait ，在执行线程的wait和notify方法前，需要获得对象的锁。获得对象锁有3中方法：
//1、执行对象的同步实例方法
//2、执行对象的同步静态方法
//3、执行对象的某一个同步锁代码块
//注意：如果对象发生改变（值改变或者引用指向其他地方），则获取改对象锁的所有线程都需要重新获取锁

public class NotifyTest0 {  
    private  String []flag = {"true"};  
    
    class NotifyThread extends Thread{  
        public NotifyThread(String name) {  
            super(name);  
        }  
        public void run() {       
            try {  
                sleep(3000);//推迟3秒钟通知  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
              synchronized (flag) {
                flag[0] = "false";  
                flag.notify();  
              }
        }  
    };  
  
    
    
    
    
    
    class WaitThread extends Thread {  
        public WaitThread(String name) {  
            super(name);  
        }  
  
        public void run() {  
              synchronized (flag) {
                while (!flag[0].equals("false")) {
                    System.out.println(getName() + " begin waiting!");  
                    long waitTime = System.currentTimeMillis();  
                    try {  
                        flag.wait();  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                    waitTime = System.currentTimeMillis() - waitTime;  
                    System.out.println("wait time :"+waitTime);  
                }  
                System.out.println(getName() + " end waiting!");  
          	}
        }  
    }  
  
    public static void main(String[] args) throws InterruptedException {  
        System.out.println("Main Thread Run!");  
        NotifyTest0 test = new NotifyTest0();  
        NotifyThread notifyThread =test.new NotifyThread("notify01");  
        WaitThread waitThread01 = test.new WaitThread("waiter01");  
        WaitThread waitThread02 = test.new WaitThread("waiter02");  
        WaitThread waitThread03 = test.new WaitThread("waiter03");  
        notifyThread.start();  
        waitThread01.start();  
        waitThread02.start();  
        waitThread03.start();  
    }  
  
}  